//
//  OAuthViewController.swift
//  我的微博
//
//  Created by Creator on 15/10/10.
//  Copyright © 2015年 Creator. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {

    // MARK: - 搭建界面
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        
        title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    
    ///  关闭界面
    func close() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLoad() {

        // 加载授权界面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
    }
    

    // MARK: - UIWebViewDelegate 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD .show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
        // 判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUri) {
        
            return true
        }
        
        print("判断参数")
        print(request.URL?.query)
        
        if let query = request.URL?.query where query.hasPrefix("code=") {
            
            print("获取授权码")
            
            // 从quer中截取授权码
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            // MARK: - 换取TOKEN
            loadAccessToken(code)
        
        }else {
            close()
        }
        
        
        return false
    }

    private func loadAccessToken(code: String) {
   
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil || result == nil {
                
                self.netError()
                return
            }
            
            // 字典转模型
            // 1. 用 token 获取的信息创建用户账户模型
            // 2. 异步加载用户信息
            // 3. 保存用户信息(模型中完成)
//            UserAccount(dict: result!).loadUserInfo(<#T##finished: (error: NSError?) -> ()##(error: NSError?) -> ()#>)
            
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                
                if error != nil {
                    self.netError()
                    
                    // 关闭
                    self.close()
                    return
                    
                }
                
                // 发送通知切换视图控制器
                NSNotificationCenter.defaultCenter().postNotificationName(ZLRootViewControllerSwitchNotification, object: false)
                
                // 关闭控制器
                self.close()
                
            })
 
        }

    }
    
    
    ///   网络出错处理
    private func netError() {
    
        SVProgressHUD.showInfoWithStatus("您的网络不给力")
        
        // 延迟一段时间在关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            self.close()
        }
        
    }
    
    
}





